package top.zhangjianyong.blog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Collection;
import java.util.List;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.zhangjianyong.blog.entity.po.RoleMenu;
import top.zhangjianyong.blog.mapper.RoleMenuMapper;
import top.zhangjianyong.blog.service.RoleMenuService;

/**
 * 角色菜单Service
 *
 * @author zhangjianyong
 * @since 2024/7/24 下午11:05
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu>
    implements RoleMenuService {

  // 把自己注册进来，需要事务的时候用
  private final RoleMenuService roleMenuService;

  public RoleMenuServiceImpl(@Lazy RoleMenuService roleMenuService) {
    this.roleMenuService = roleMenuService;
  }

  @Override
  public boolean remove(Long roleId, Collection<Long> menuIds) {
    return CollectionUtils.isEmpty(menuIds)
        || lambdaUpdate().eq(RoleMenu::getRoleId, roleId).in(RoleMenu::getMenuId, menuIds).remove();
  }

  @Override
  public boolean save(Long roleId, Collection<Long> menuIds) {
    if (CollectionUtils.isEmpty(menuIds)) return true;
    List<RoleMenu> roleMenus =
        menuIds.stream()
            .map(
                menuId -> {
                  RoleMenu roleMenu = new RoleMenu();
                  roleMenu.setRoleId(roleId);
                  roleMenu.setMenuId(menuId);
                  return roleMenu;
                })
            .toList();

    return roleMenuService.saveBatch(roleMenus);
  }

  @Override
  public void removeByRole(Long roleId) {
    lambdaUpdate().eq(RoleMenu::getRoleId, roleId).remove();
  }

  @Override
  public boolean removeByMenu(Long menuId) {
    return lambdaUpdate().eq(RoleMenu::getMenuId, menuId).remove();
  }
}
